package game.metalmax.ui
{
	import flash.display.DisplayObjectContainer;
	
	import game.metalmax.controller.Notifications;
	import game.metalmax.ui.common.Preloader001;
	import game.metalmax.ui.main.AlertWindow;
	
	import showtime.framework.component.loading.GroupLoader;
	import showtime.framework.component.loading.GroupLoaderEvent;
	import showtime.framework.component.loading.NowLoading;
	import showtime.framework.manager.WindowManager;
	import showtime.framework.motion.EazeTween;
	import showtime.framework.motion.eaze;
	import showtime.framework.mvc.interfaces.INotification;
	import showtime.framework.mvc.patterns.mediator.Mediator;

	public class GuideLayerMediator extends Mediator
	{
		private var parent:Object = null;
		
		public function GuideLayerMediator(parent:Object)
		{
			super(String(GuideLayerMediator));
			this.parent = parent;
		}
		
		override public function onRegister():void
		{
			super.onRegister();
			
			viewComponent = new GuideLayer();
			parent.addChild(viewComponent);	
		}
		
		override public function onRemove():void
		{
			super.onRemove();
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch (notification.getName())
			{
				case Notifications.NOW_LOADING:
				{
					nowloading(notification.getBody());
					break;
				}
				case Notifications.OPEN_ALERT_WINDOW:
				{
					openAlertWindow(notification.getBody());
					break;
				}
			}
		}
		
		override public function listNotificationInterests():Array
		{
			return [Notifications.NOW_LOADING, Notifications.OPEN_ALERT_WINDOW];
		}
		
		private function nowloading(body:Object):void
		{
			var _nowloading:NowLoading = new NowLoading(null, new Preloader001());
			viewComponent.addChild(_nowloading);
			var loader:GroupLoader = new GroupLoader();
			
			for each (var url:String in body.data)
			{
				loader.addURL(url);
			}			
		
			loader.addEventListener(GroupLoaderEvent.PROGRESS, progressHandler);
			loader.addEventListener(GroupLoaderEvent.COMPLETE, completeHandler);
			loader.start();
			
			
			function completeHandler(evt:GroupLoaderEvent):void
			{			
				loader.removeEventListener(GroupLoaderEvent.COMPLETE, completeHandler);
				loader.removeEventListener(GroupLoaderEvent.PROGRESS, progressHandler);
				
				body.method(loader);
				eaze(_nowloading).delay(0.5).to(0.2, {alpha:0}).onComplete(function():void{body.source.active = true;_nowloading.destroy();EazeTween.killAllTweens();});
				
			}
			
			function progressHandler(evt:GroupLoaderEvent):void
			{
				_nowloading.update(evt);
			}
		}
		
		private function openAlertWindow(data:Object):void
		{
			sendNotification(Notifications.DEACTIVATE_ZONE);
			
			WindowManager.centerPopUp(WindowManager.createPopUp(AlertWindow, DisplayObjectContainer(viewComponent), true)).refresh(data);
		}
	}
}